<?php
/**
 * Created by PhpStorm.
 * User: DELL-PC
 * Date: 2018/8/2
 * Time: 22:45
 */

namespace Aoe\Emulator\Processor;


use Aoe\Emulator\Schema\Model;
use Exception;

/**
 * # Group/Order/Limit 语句
 */
class Addition
{
    const string GROUP = 'group';
    const string LIMIT = 'limit';
    const string ORDER = 'order';
    
    /**
     * @var array
     * @noinspection PhpGetterAndSetterCanBeReplacedWithPropertyHooksInspection
     */
    private array $options = [];

    /**
     * Option constructor.
     *
     * @param Model $model
     */
    public function __construct(protected Model $model) {}
    
    public function getOptions(): array
    {
        return $this->options;
    }
    
    /**
     * groupBy语句
     *
     * @param ?string $name
     *
     * @return static
     * @throws Exception
     * @noinspection PhpUnused
     */
    public function groupBy(?string $name = null): Addition
    {
        $this->options[self::GROUP] = $this->model->getElement($name)->getColumn();
        return $this;
    }
    
    /**
     * order 语句
     *
     * @param string $name
     * @param bool   $asc
     *
     * @return static
     * @throws Exception
     */
    public function orderBy(string $name, bool $asc = true): Addition
    {
        $this->options[self::ORDER][$this->model->getElement($name)->getColumn()] = $asc;
        return $this;
    }
    
    /**
     * @param int $m 起始页数
     * @param int $n 每页条数
     *
     * @return $this
     */
    public function page(int $m, int $n): Addition
    {
        if ($n <= 0) return $this;
        if ($m <= 1) return $this->top($n);
        
        $this->options[self::LIMIT] = [($m - 1) * $n, $n];
        return $this;
    }
    
    public function top($n): Addition
    {
        $n = (int)$n;
        if ($n > 0) $this->options[self::LIMIT] = (int)$n;
        return $this;
    }
}